﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace ArienToolkits.Cryptography
{
    /// <summary>
    /// AES算法加密类
    /// </summary>
    public static class AES
    {
        //向量值(建议在使用时修改)
        private static readonly string IV = "Cg@7VD$7anCdYAT7";

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="srcText">原始字符串</param>
        /// <param name="aesKey">加密Key</param>
        /// <returns></returns>
        public static string Encrypt(string srcText, string aesKey)
        {
            aesKey = aesKey.PadRight(32, ' ');
            ICryptoTransform transform = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(aesKey.Substring(0, 32)),
                IV = Encoding.Default.GetBytes(IV)
            }.CreateEncryptor();
            byte[] bytes = Encoding.UTF8.GetBytes(srcText);
            return Convert.ToBase64String(transform.TransformFinalBlock(bytes, 0, bytes.Length));
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="srcText">加密字符串</param>
        /// <param name="aesKey">解密Key</param>
        /// <returns></returns>
        public static string Decrypt(string srcText, string aesKey)
        {
            try
            {
                aesKey = aesKey.PadRight(32, ' ');
                ICryptoTransform transform = new RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(aesKey),
                    IV = Encoding.Default.GetBytes(IV)
                }.CreateDecryptor();
                byte[] inputBuffer = Convert.FromBase64String(srcText);
                byte[] bytes = transform.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
                return Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return string.Empty;
            }
        }

        #region 扩展方法
        /// <summary>
        /// AES加密算法
        /// </summary>
        /// <param name="srcText">需要加密的字符串</param>
        /// <param name="aesKey">加密密钥</param>
        /// <returns></returns>
        public static string ToEncryptAES(this string srcText, string aesKey)
        {
            return Encrypt(srcText, aesKey);
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="srcText">需要被解密的字符串</param>
        /// <param name="aesKey">解密密钥</param>
        /// <returns></returns>
        public static string ToDecryptAES(this string srcText, string aesKey)
        {
            return Decrypt(srcText, aesKey);
        }
        #endregion
    }
}
